package com.example.asus_pc.myshop.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.asus_pc.myshop.R;
import com.example.asus_pc.myshop.bean.User;

import java.util.ArrayList;
import java.util.List;

public class AddNamePrice extends AppCompatActivity {

    private EditText et_num;
    private EditText et_price;

    private TextView tv1;// Veg_num
    private TextView tv2;//item.xml里的TextView：Veg_name
    private TextView tv3;//item.xml里的TextView：Veg_price
    private TextView tvtv;
    private Button bt;//xml里的Button
    private ListView lv;//xml里的ListView
    private BaseAdapter adapter;//要实现的类
    private List<User> userList = new ArrayList<User>();//实体类
    private AlertDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_name_price);
        bt = (Button) findViewById(R.id.Button);
        lv = (ListView) findViewById(R.id.lv_name_price);

        et_num = (EditText)findViewById(R.id.et_num);
        et_price = (EditText)findViewById(R.id.et_price);

        SharedPreferences userVeg = getSharedPreferences("Veg", 0);

        String[] Vegs = {"鸡蛋","白条鸡","韭菜","茴香","香菜","小葱","青椒","尖椒","黄瓜","西红柿","土豆","茄子","西湖",
                "长豆角","无丝豆","大扁","白葱头","红葱头","胡萝卜","白萝卜","大葱","大白菜","甘蓝","有机菜花",
                "西兰花","菜花","杭椒","金瓜","小绿瓜","苦瓜","丝瓜","姜","蒜苔","蒜苗","蒜黄","花生","毛豆",
                "红椒","娃娃菜","蒜米","水芹","香亭","豆苗","金针菇","白玉菇","杏鲍菇","香菇","根达菜","生菜",
                "油麦","油菜","圆生菜","小白菜","空心菜","苦菊","菠菜","豆芽","豆嘴","大蒜","藕","片粉","豆皮",
                "豆腐","豆腐丝","烧饼","拉皮（大）","拉皮","土豆粉","马粉","十八里（散）","十八里（1斤）",
                "王家粉条","玉米面","玉米茬","绿豆","香蕉","苹果","桃","葡萄","火龙果","橘子","橙子","西瓜",
                "梨","花卷","凉皮","面条","饼条","扁豆角","荷兰豆","绿白菜","紫甘蓝","线椒","米椒","美人椒","元丝瓜","大冬瓜","小冬瓜"
        };

        for (int i = 0; i < Vegs.length; i++) {
            User ue = new User();//给实体类赋值
            ue.setNum(String.valueOf(i+1));
            ue.setName(Vegs[i]);
            String price = userVeg.getString(Vegs[i],"1.0");
            ue.setPrice(price + "元/斤");
            userList.add(ue);
        }

        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return userList.size();//数目
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = AddNamePrice.this.getLayoutInflater();
                View view;

                if (convertView==null) {
                    //因为getView()返回的对象，adapter会自动赋给ListView
                    view = inflater.inflate(R.layout.item, null);
                }else{
                    view=convertView;
                    Log.i("info","有缓存，不需要重新生成"+position);
                }

                tv1 = (TextView)view.findViewById(R.id.Veg_num);
                tv1.setText(userList.get(position).getNum());

                tv2 = (TextView)view.findViewById(R.id.Veg_name);//找到Veg_name
                tv2.setText(userList.get(position).getName());//设置参数

                tv3 = (TextView)view.findViewById(R.id.Veg_price);//找到Veg_name
                tv3.setText(userList.get(position).getPrice());//设置参数

                return view;
            }
        };
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:    //当停止滚动时
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:    //滚动时

                        //没错，下面这一坨就是隐藏软键盘的代码
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddNamePrice.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:   //手指抬起，但是屏幕还在滚动状态
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

            //获取当前ListView点击的行数，并且得到该数据
        /*
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String str;
                    tv1 = (TextView) view.findViewById(R.id.Veg_name);//找到Textviewname
                    str = tv1.getText().toString();//得到数据
                    Toast.makeText(AddNamePrice.this, "" + str, Toast.LENGTH_SHORT).show();//显示数据

                   // ((TextView) view).setText(tv1.getText().toString());


                }
            });*/
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                setAlertDialog(view);
                dialog.show();
                return false;
            }
        });
        lv.setAdapter(adapter);
    }

    private void setAlertDialog(final View view) {
        LayoutInflater factory = LayoutInflater.from(getApplicationContext());
        // 引入一个外部布局
        View contview = factory.inflate(R.layout.test_dialog, null);
        contview.setBackgroundColor(Color.BLACK);// 设置该外部布局的背景
        final EditText edit = (EditText) contview.findViewById(R.id.edit_dialog);// 找到该外部布局对应的EditText控件
        Button btOK = (Button) contview.findViewById(R.id.btOK_dialog);
        String str;
        tvtv = (TextView) view.findViewById(R.id.Veg_name);//找到Textviewname
        str = tvtv.getText().toString();//得到数据

        tvtv = (TextView) contview.findViewById(R.id.tv_dialog);
        tvtv.setText(str);
        String strnum = et_num.getText().toString();
        final int num = Integer.parseInt(strnum);
        final User ue = userList.get(num-1);

        btOK.setOnClickListener(new View.OnClickListener() {// 设置按钮的点击事件

            @Override
            public void onClick(View v) {

                ue.setPrice(edit.getText().toString() + "元/斤");
                userList.set(num-1, ue);
                lv.setAdapter(adapter);
//                ((TextView)findViewById(R.id.Veg_price)).setText(edit.getText().toString());
//                ((TextView) view).setText(edit.getText().toString());
                dialog.dismiss();
            }
        });
        dialog = new AlertDialog.Builder(AddNamePrice.this).setView(contview)
                .create();
    }

    public void add_name_price_button(View view) {

        String strnum = et_num.getText().toString();
        int num = Integer.parseInt(strnum);
        String Strprice = et_price.getText().toString();
        float price = Float.parseFloat(Strprice);
        if(num<1 || num > userList.size()|| price <=0 || price >=1000)
            return;

        User ue = userList.get(num-1);
        String name = ue.getName();
        ue.setPrice(Strprice + "元/斤");
        userList.set(num-1, ue);
        lv.setAdapter(adapter);

        SharedPreferences userVeg = getSharedPreferences("Veg", 0);
        SharedPreferences.Editor editor = userVeg.edit();
        editor.putString(name,Strprice);
        editor.commit();

    }
}

